package cn.yu.meeting.login.controller;

import cn.yu.meeting.common.pojo.Result;
import cn.yu.meeting.common.utils.JwtUtil;
import cn.yu.meeting.user.pojo.User;
import cn.yu.meeting.login.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Objects;

@RestController
@RequestMapping("/login")
public class LoginController {


    @Autowired
    private LoginService loginService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 手机号登录
     *
     * @param account 账号
     * @param pwd     密码
     */
    @PostMapping("/loginByMobile")
    public Result loginByMobile(String account, String pwd) {
        User user = loginService.findByAccount(account);
        if (user == null) {
            return Result.error("用户不存在");
        }
        //比对密码是否正确
        if (Objects.equals(user.getPwd(), pwd)) {
            //生成token,并返回给客户端
            HashMap<String, Object> claims = new HashMap<>();
            claims.put("id", user.getId());
            claims.put("account", user.getAccount());
            String token = JwtUtil.genToken(claims);

            //存储一下token到redis
            ValueOperations<String, String> stringStringValueOperations = stringRedisTemplate.opsForValue();
            stringStringValueOperations.set(token, token);
            return Result.success(token);
        } else {
            return Result.error("密码错误");
        }
    }

    /**
     * 这是一个根据手机号注册的接口
     *
     * @param account 账号
     * @param pwd     密码
     */
    @PostMapping("/registerByMobile")
    public Result<User> registerByMobile(@RequestParam String account, @RequestParam String pwd) {
        User user = loginService.findByAccount(account);
        if (user == null) {
            /*
             * 没有找到
             */
            loginService.registerByMobile(account, pwd);
            return Result.success();
        } else {
            /*
             * 找到了
             */
            return Result.error("您已注册过了,请直接登录");
        }

    }
}
